package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public JsonResult select(VehicleQuery vehicleQuery) {
        List<VehicleVO> vehicleVOList = vehicleMapper.select(vehicleQuery);
        return JsonResult.ok(vehicleVOList);
    }

    @Override
    public JsonResult save(VehicleSaveParam vehicleSaveParam) {
        if (vehicleSaveParam.getId()==null){
            VehicleQuery vehicleQuery = new VehicleQuery();
            vehicleQuery.setLicense(vehicleSaveParam.getLicense());
            List<VehicleVO> vos = vehicleMapper.select(vehicleQuery);
            if(!vos.isEmpty()){
                throw new ServiceException(StatusCode.VEHICLE_ALREADY_EXISTS);
            }
            Vehicle vehicle = new Vehicle();
            BeanUtils.copyProperties(vehicleSaveParam,vehicle);
            vehicle.setCreateTime(new Date());
            vehicle.setUpdateTime(new Date());
            vehicle.setStatus("1");
            vehicleMapper.saveVehicle(vehicle);
            return JsonResult.ok();
        }else {
            vehicleSaveParam.setUpdateTime(new Date());
            vehicleMapper.update(vehicleSaveParam);
            return JsonResult.ok();
        }
    }

    @Override
    public JsonResult del(Long id) {
        vehicleMapper.del(id);
        return JsonResult.ok();
    }
}
